<template>
	<view class="post-container">
		<!-- 标题头部 -->
		<view class="page-header">
			<text class="title">发布帖子</text>
		</view>
		
		<view class="form-container">
			<!-- 帖子标题 -->
			<view class="form-item">
				<text class="form-label">标题</text>
				<input 
					class="form-input" 
					type="text" 
					v-model="formData.title"
					placeholder="请输入帖子标题（5-30字）"
					maxlength="30"
				/>
			</view>
			
			<!-- 帖子内容 -->
			<view class="form-item">
				<text class="form-label">内容</text>
				<textarea 
					class="form-textarea" 
					v-model="formData.content"
					placeholder="请输入帖子内容..."
					maxlength="1000"
				/>
				<view class="word-count">{{ formData.content.length }}/1000</view>
			</view>
			
			<!-- 标签选择 -->
			<view class="form-item">
				<text class="form-label">选择标签</text>
				<view class="tag-list">
					<view 
						class="tag-item" 
						v-for="(tag, index) in tags" 
						:key="index"
						:class="{ active: formData.tagId === tag.id }"
						:style="formData.tagId === tag.id ? { backgroundColor: tag.color, color: '#fff' } : {}"
						@tap="selectTag(tag.id)"
					>
						{{ tag.name }}
					</view>
				</view>
			</view>
			
			<!-- 图片上传 -->
			<view class="form-item">
				<text class="form-label">添加图片 (选填，最多3张)</text>
				<view class="image-upload">
					<view class="image-list">
						<view 
							class="image-item" 
							v-for="(image, index) in formData.images" 
							:key="index"
						>
							<image :src="image" mode="aspectFill" class="preview-image" />
							<view class="delete-btn" @tap="deleteImage(index)">×</view>
						</view>
						
						<view class="upload-btn" @tap="chooseImage" v-if="formData.images.length < 3">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传图片</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 匿名设置 -->
			<view class="form-item">
				<view class="switch-item">
					<text class="switch-label">匿名发布</text>
					<switch :checked="formData.isAnonymous" @change="toggleAnonymous" color="#8cc9a1" />
				</view>
				<text class="form-tip">{{ formData.isAnonymous ? '开启后，您的用户名将显示为随机昵称' : '关闭后，将使用您的真实昵称和头像' }}</text>
			</view>
			
			<!-- 按钮组 -->
			<view class="btn-group">
				<button class="btn-cancel" @tap="goBack">取消</button>
				<button class="btn-submit" @tap="submitForm">发布</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive } from 'vue'
	import { createPost } from '@/common/api/community.js'
	import { getUserInfo } from '@/common/utils/auth.js'
	
	// 确保__route__存在
	if (typeof __route__ === 'undefined') {
		try {
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			// @ts-ignore
			global.__route__ = currentPage.route;
		} catch (e) {
			console.error('获取当前页面路径失败:', e);
			// @ts-ignore
			global.__route__ = '/pages/community/post';
		}
	}
	
	// 标签列表
	const tags = [
		{ id: 1, name: '求助', color: '#f0ad4e' },
		{ id: 2, name: '分享', color: '#5bc0de' },
		{ id: 3, name: '讨论', color: '#d9534f' },
		{ id: 4, name: '经验', color: '#9370db' },
		{ id: 5, name: '饮食', color: '#28a745' },
		{ id: 6, name: '运动', color: '#fd7e14' },
		{ id: 7, name: '科普', color: '#17a2b8' }
	]
	
	// 表单数据
	const formData = reactive({
		title: '',
		content: '',
		tagId: 0,
		images: [],
		isAnonymous: true
	})
	
	// 选择标签
	const selectTag = (tagId) => {
		formData.tagId = tagId
	}
	
	// 切换匿名状态
	const toggleAnonymous = (e) => {
		formData.isAnonymous = e.detail.value
	}
	
	// 选择图片
	const chooseImage = () => {
		uni.chooseImage({
			count: 3 - formData.images.length,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				// 这里应该上传图片到服务器，获取URL
				// 但在模拟环境中，我们直接使用本地路径
				formData.images = [...formData.images, ...res.tempFilePaths]
			}
		})
	}
	
	// 删除图片
	const deleteImage = (index) => {
		formData.images.splice(index, 1)
	}
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
	
	// 表单验证
	const validateForm = () => {
		if (!formData.title.trim()) {
			uni.showToast({
				title: '请输入帖子标题',
				icon: 'none'
			})
			return false
		}
		
		if (formData.title.trim().length < 5) {
			uni.showToast({
				title: '标题至少5个字',
				icon: 'none'
			})
			return false
		}
		
		if (!formData.content.trim()) {
			uni.showToast({
				title: '请输入帖子内容',
				icon: 'none'
			})
			return false
		}
		
		if (formData.content.trim().length < 10) {
			uni.showToast({
				title: '内容至少10个字',
				icon: 'none'
			})
			return false
		}
		
		if (formData.tagId === 0) {
			uni.showToast({
				title: '请选择一个标签',
				icon: 'none'
			})
			return false
		}
		
		return true
	}
	
	// 提交表单
	const submitForm = async () => {
		// 表单验证
		if (!validateForm()) return
		
		uni.showLoading({
			title: '发布中...'
		})
		
		try {
			// 准备提交数据
			const postData = {...formData}
			
			// 生成匿名用户信息
			if (postData.isAnonymous) {
				// 匿名用户颜色列表
				const userColors = [
					'#8cc9a1', '#5bc0de', '#f0ad4e', '#d9534f', '#9370db', '#20b2aa', '#ff7f50', '#6495ed'
				]
				
				// 匿名用户昵称前缀
				const nicknamePrefix = [
					'糖友', '健康', '阳光', '快乐', '幸福', '勇敢', '坚强', '智慧',
					'温暖', '善良', '乐观', '平静', '活力', '希望', '自信', '从容'
				]
				
				// 随机生成颜色和昵称
				const colorIndex = Math.floor(Math.random() * userColors.length)
				const prefixIndex = Math.floor(Math.random() * nicknamePrefix.length)
				const randomNum = Math.floor(Math.random() * 1000)
				
				postData.userColor = userColors[colorIndex]
				postData.userNickname = `${nicknamePrefix[prefixIndex]}${randomNum}`
			} else {
				// 非匿名，使用用户真实信息
				const userInfo = getUserInfo()
				if (userInfo) {
					postData.userNickname = userInfo.nickname || userInfo.username || '用户'
					postData.userAvatar = userInfo.avatar || ''
					// 设置一个默认颜色，避免前端显示问题
					postData.userColor = '#8cc9a1'
				}
			}
			
			// 移除isAnonymous字段，后端不需要
			delete postData.isAnonymous
			
			// 调用API发布帖子
			const res = await createPost(postData)
			
			if (res.code === 0) {
				// 隐藏加载中
				uni.hideLoading()
				
				// 显示发布成功的模态框
				uni.showModal({
					title: '发布成功',
					content: '您的帖子已成功发布到社区',
					showCancel: false,
					success: () => {
						// 返回上一页并刷新列表
						const pages = getCurrentPages()
						const prevPage = pages[pages.length - 2]
						
						// 如果存在上一页，刷新其数据
						if (prevPage && prevPage.$vm) {
							// 尝试调用上一页的刷新方法
							if (typeof prevPage.$vm.loadPosts === 'function') {
								prevPage.$vm.loadPosts()
							}
						}
						
						uni.navigateBack()
					}
				})
			} else {
				throw new Error(res.message || '发布失败')
			}
		} catch (e) {
			console.error('发布帖子失败:', e)
			uni.showToast({
				title: typeof e === 'string' ? e : '发布失败，请重试',
				icon: 'none',
				duration: 2000
			})
			uni.hideLoading()
		}
	}
</script>

<style lang="scss">
	.post-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		
		.page-header {
			background-color: #8cc9a1;
			padding: 30rpx;
			padding-top: 60rpx;
			
			.title {
				color: #fff;
				font-size: 38rpx;
				font-weight: 600;
			}
		}
		
		.form-container {
			padding: 30rpx;
			
			.form-item {
				background-color: #fff;
				border-radius: 12rpx;
				padding: 20rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
				position: relative;
				
				.form-label {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
					margin-bottom: 15rpx;
					display: block;
				}
				
				.form-input {
					width: 100%;
					height: 80rpx;
					font-size: 30rpx;
					border-bottom: 1px solid #eee;
					padding: 10rpx 0;
				}
				
				.form-textarea {
					width: 100%;
					height: 300rpx;
					font-size: 30rpx;
					line-height: 1.5;
					padding: 10rpx 0;
				}
				
				.word-count {
					text-align: right;
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
				}
				
				.tag-list {
					display: flex;
					flex-wrap: wrap;
					margin: 0 -10rpx;
					
					.tag-item {
						padding: 15rpx 30rpx;
						margin: 10rpx;
						font-size: 28rpx;
						color: #666;
						background-color: #f5f5f5;
						border-radius: 30rpx;
						
						&.active {
							color: #fff;
						}
					}
				}
				
				.image-upload {
					.image-list {
						display: flex;
						flex-wrap: wrap;
						margin: 0 -10rpx;
						
						.image-item {
							width: 200rpx;
							height: 200rpx;
							margin: 10rpx;
							position: relative;
							
							.preview-image {
								width: 100%;
								height: 100%;
								border-radius: 8rpx;
							}
							
							.delete-btn {
								position: absolute;
								top: -15rpx;
								right: -15rpx;
								width: 40rpx;
								height: 40rpx;
								background-color: rgba(0, 0, 0, 0.5);
								color: #fff;
								border-radius: 50%;
								display: flex;
								align-items: center;
								justify-content: center;
								font-size: 28rpx;
							}
						}
						
						.upload-btn {
							width: 200rpx;
							height: 200rpx;
							margin: 10rpx;
							background-color: #f5f5f5;
							border-radius: 8rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							
							.upload-icon {
								font-size: 50rpx;
								color: #999;
								margin-bottom: 10rpx;
							}
							
							.upload-text {
								font-size: 24rpx;
								color: #999;
							}
						}
					}
				}
				
				.switch-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					
					.switch-label {
						font-size: 28rpx;
						color: #333;
					}
				}
				
				.form-tip {
					font-size: 24rpx;
					color: #999;
					margin-top: 10rpx;
					display: block;
				}
			}
			
			.btn-group {
				display: flex;
				margin-top: 40rpx;
				
				.btn-cancel, .btn-submit {
					flex: 1;
					height: 90rpx;
					line-height: 90rpx;
					text-align: center;
					border-radius: 45rpx;
					font-size: 32rpx;
				}
				
				.btn-cancel {
					background-color: #f0f2f5;
					color: #666;
					margin-right: 20rpx;
				}
				
				.btn-submit {
					background: linear-gradient(135deg, #8cc9a1 0%, #6eb888 100%);
					color: #fff;
					box-shadow: 0 4rpx 10rpx rgba(110, 184, 136, 0.3);
				}
			}
		}
	}
</style> 